package com.zl.controller;

import com.zl.common.Result;
import com.zl.dto.TsMenuDto;
import com.zl.entity.TsMenu;
import com.zl.entity.TsUser;
import com.zl.security.SecurityUtils;
import com.zl.service.MenuService;
import com.zl.service.RoleService;
import com.zl.service.UserService;
import com.zl.util.Exceptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("menu")
@Slf4j
public class MenuController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 构建前端路由所需要的菜单
     * @return
     */
    @GetMapping(value = "/build")
    public Result buildMenus(){
        TsUser user = userService.findByName(SecurityUtils.getUsername());
        List<TsMenu> menus = menuService.findByRoles(roleService.findByUsersId(user.getId()));
        List<TsMenu> menusTree = (List<TsMenu>)menuService.buildTree(menus).get("content");
        return Result.success(menuService.buildMenus(menusTree));
    }

    /**
     * 返回全部的菜单
     * @return
     */
    @GetMapping(value = "/tree")
    //@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_CREATE','MENU_EDIT','ROLES_SELECT','ROLES_ALL')")
    public Result getMenuTree(){
        return menuService.getMenuTree();
    }

    @GetMapping(value = "/all")
    //@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_SELECT')")
    public Result getMenus(TsMenuDto menuDto){
        try {
            List<TsMenu> menus = menuService.all(menuDto);
            return Result.success(menuService.buildTree(menus));
        } catch (Exception e) {
            log.error("查询菜单异常：{}", Exceptions.getStackTraceAsString(e));
            return Result.error();
        }
    }

    @PostMapping(value = "/add")
    //@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_CREATE')")
    public Result create(@Validated @RequestBody TsMenuDto resources){
        try {
            return menuService.create(resources);
        } catch (Exception e) {
            log.error("创建菜单异常：{}", Exceptions.getStackTraceAsString(e));
            return Result.error();
        }
    }

    @PutMapping(value = "/upt")
    //@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_EDIT')")
    public Result update(@RequestBody TsMenuDto resources){
        try {
            return menuService.update(resources);
        } catch (Exception e) {
            log.error("修改菜单异常：{}", Exceptions.getStackTraceAsString(e));
            return Result.error();
        }
    }

    @DeleteMapping(value = "/menus/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_DELETE')")
    public Result delete(@PathVariable Long id){
        return menuService.delete(id);
    }
}
